package com.song.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.DigestUtils;

import java.security.SecureRandom;
import java.util.Base64;

public class Md5WithSalt {
    private static final Log log = LogFactory.getLog(Md5WithSalt.class);

    //md5 + 盐值 加密
    public static String salttedMd5(String str) {
        //1.生成一个随机的盐值
        byte[] salt = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);
        String saltStr = Base64.getEncoder().encodeToString(salt); // 转为Base64字符串便于存储

        //2.将盐值和需要加密的字符串进行md5加密
        String salttedStr = str + saltStr;
        String md5WithSalt = DigestUtils.md5DigestAsHex(salttedStr.getBytes());
        return md5WithSalt + "." +saltStr;
    }
    //验证Md5加盐的数据
    public static boolean verifySalttedMd5(String Md5hash, String str) {
        //获取加密前的盐值 + 加密后的字符串
        System.out.println(Md5hash);
        String[] split = Md5hash.split("\\.");
        String salt = split[1];
        String md5WithSalt = DigestUtils.md5DigestAsHex((str + salt).getBytes());
        return md5WithSalt.equals(split[0]);
    }
}
